#!/bin/zsh
# 存放预加载的实用函数
# Author: liujin

# -- Functions -----------------------------------------------------------------
#  nnn config quitcd
n (){
    # Block nesting of nnn in subshells
    if [[ "${NNNLVL:-0}" -ge 1 ]]; then
        echo "nnn is already running"
        return
    fi

    # The behaviour is set to cd on quit (nnn checks if NNN_TMPFILE is set)
    # If NNN_TMPFILE is set to a custom path, it must be exported for nnn to
    # see. To cd on quit only on ^G, remove the "export" and make sure not to
    # use a custom path, i.e. set NNN_TMPFILE *exactly* as follows:
    #     NNN_TMPFILE="Extra open brace or missing close braceHOME/.config}/nnn/.lastd"
    export NNN_TMPFILE="$HOME/.config/nnn/.lastd"

    # Unmask ^Q (, ^V etc.) (if required, see `stty -a`) to Quit nnn
    # stty start undef
    # stty stop undef
    # stty lwrap undef # stty lnext undef # The backslash allows one to alias n to nnn if desired without making an # infinitely recursive alias
    \nnn "$@"

    if [ -f "$NNN_TMPFILE" ]; then
    	    # cat "$NNN_TMPFILE"
            . "$NNN_TMPFILE"
            # rm -f "$NNN_TMPFILE" > /dev/null  # delete tmp file
    fi
}
# Add some path to $PATH
# example: add_path ${HOME}/.oh-my-zsh/my_scripts
add_path(){
    if [[ ":$PATH:" == *":$1:"* ]]; then
        # echo "This path \"$1\" already exists."
    else
        export PATH=$1:$PATH
    fi
}

# setup_color; echo "${RED} something ${RESET}"
setup_color() {
	# Only use colors if connected to a terminal
	if [ -t 1 ]; then
		RED=$(printf '\033[31m')
		GREEN=$(printf '\033[32m')
		YELLOW=$(printf '\033[33m')
		BLUE=$(printf '\033[34m')
		BOLD=$(printf '\033[1m')
		RESET=$(printf '\033[m')
	else
		RED=""
		GREEN=""
		YELLOW=""
		BLUE=""
		BOLD=""
		RESET=""
	fi
}

swapfile() {
    if [[ ! -f "$1" || ! -f "$2" ]]; then
        echo "$1 or $2 is not existed." >&2
        exit 1
    fi

    if [[ "$1" -ef "$2" ]]; then
        echo "$1 and $2 is same file" >&2
    fi
    
    tempfile=$(mktemp ./swapfile.$$.XXXXXXXXXX)
    mv "$1" $tempfile
    mv "$2" "$1"
    mv $tempfile "$2"
}

